<?php

namespace app\department\controller;

use app\department\model\DepartmentConfigModel;
use app\department\model\RoleModel;
use cmf\controller\AdminBaseController;
use tree\Tree;

class PositionController extends AdminBaseController
{
    /**
     * 职位列表
     * @adminMenu(
     *     'name'   => '职位列表',
     *     'parent' => 'department/department/index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '职位列表',
     *     'param'  => ''
     * )
     */
    function index()
    {
        $department_id = $this->request->param('department_id', 0, 'intval');
        if (!$department_id) {
            $this->error('非法参数');
        }
        $roleModel = new RoleModel();
        $lists = $roleModel
            ->where([
                'department_id' => $department_id,
                'status' => 1
            ])
            ->paginate();

        $page = $lists->render();
        $this->assign('lists', $lists);
        $this->assign('page', $page);
        $this->assign('department_id', $department_id);

        return $this->fetch();
    }

    /**
     * 添加
     * @adminMenu(
     *     'name'   => '添加',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '添加',
     *     'param'  => ''
     * )
     */
    function add()
    {
        $department_id = $this->request->param('department_id', 0, 'intval');
        if (!$department_id) {
            $this->error('非法参数');
        }
        if ($this->request->isPost()) {
            $arrData = $this->request->post();
            $roleModel = new RoleModel();
            $result = $roleModel->allowField(true)->validate(true)->save($arrData);
            if ($result) {
                $this->success('添加成功', url('index',['department_id' => $department_id]));
            } else {
                $this->error($roleModel->getError());
            }
        }
        $this->assign('department_id', $department_id);
        return $this->fetch();
    }

    /**
     * 编辑
     * @adminMenu(
     *     'name'   => '编辑',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '编辑',
     *     'param'  => ''
     * )
     */
    function edit()
    {
        if ($this->request->isPost()) {
            $arrData = $this->request->post();
            if (empty($arrData['id'])) {
                $this->error('参数错误');
            }
            $roleModel = new RoleModel();
            $result = $roleModel->allowField(true)->validate(true)->save($arrData, ['id' => $arrData['id']]);
            if ($result) {
                $this->success('编辑成功', url('index',['department_id' => $arrData['department_id']]));
            } else {
                $this->error($roleModel->getError());
            }
        }
        $id = $this->request->param("id", 0, 'intval');
        $roleModel = new RoleModel();
        $result = $roleModel->find($id);
        if (!$result) {
            $this->error('非法参数');
        } else {
            $this->assign('result', $result);
            return $this->fetch();
        }
    }

    public function select()
    {
        $id = $this->request->param('id', 0, 'intval');
        $parent_id = $this->request->param('parent_id', 0, 'intval');

        $where = ['status' => 1, 'department_id' => $parent_id];
        $roleModel = new RoleModel();
        $lists = $roleModel->where($where)->select();

        $this->assign('lists', $lists);
        $this->assign('id', $id);
        return $this->fetch();
    }

    function del() {
        $id = $this->request->param('id',0,'intval');
        $role_user = db('role_user')
            ->alias('role_user')
            ->join('__USER__ user','role_user.user_id = user.id')
            ->where([
                'role_id' => $id,
                'user.user_status' => 1
            ])
            ->find();
        if($role_user) {
            $this->error('请先处理该职位下的员工！');
        }
        $roleModel = new RoleModel();
        $roleModel
            ->save([
                'status' => 0,
            ],[
                'id' => $id
            ]);
        $this->success('删除成功！');
    }

    /**
     * 授权
     * @adminMenu(
     *     'name'   => '授权',
     *     'parent' => 'index',
     *     'display'=> false,
     *     'hasView'=> true,
     *     'order'  => 10000,
     *     'icon'   => '',
     *     'remark' => '授权',
     *     'param'  => ''
     * )
     */
    public function authority()
    {
        if ($this->request->isPost()) {
            $roleId = $this->request->param("roleId", 0, 'intval');
            if (!$roleId) {
                $this->error("需要授权的职位不存在！");
            }
            if (is_array($this->request->param('menuId/a')) && count($this->request->param('menuId/a')) > 0) {

                db("authAccess")->where(["role_id" => $roleId, 'type' => 'admin_url'])->delete();
                foreach ($_POST['menuId'] as $menuId) {
                    $menu = db("adminMenu")->where(["id" => $menuId])->field("app,controller,action")->find();
                    if ($menu) {
                        $app = $menu['app'];
                        $model = $menu['controller'];
                        $action = $menu['action'];
                        $name = strtolower("$app/$model/$action");
                        db("authAccess")->insert(["role_id" => $roleId, "rule_name" => $name, 'type' => 'admin_url']);
                    }
                }

                $roleDepartment = db('role_department')->where([
                    'role_id' => $roleId
                ])->find();
                $data['show_department'] = $this->request->post('show_department',0);
                $data['data_to_all_user'] = $this->request->post('data_to_all_user',0);
                $data['company_manage'] = $this->request->post('company_manage',0);
                foreach ($data as &$val) {
                    if($val) $val = 1;
                }
                if($roleDepartment) {
                    db('role_department')->where([
                        'role_id' => $roleId
                    ])->update($data);
                }else{
                    $data['role_id'] = $roleId;
                    db('role_department')->insert($data);
                }

                db('role_item')->where([
                    'role_id' => $roleId
                ])->delete();
                $user_items = $this->request->post('user_item/a');
                $items = [];
                if($user_items) {
                    foreach ($user_items as $key => $val) {
                        $items[] = [
                            'role_id' => $roleId,
                            'config_id' => $key,
                            'item_id' => $val,
                        ];
                    }
                    db('role_item')->insertAll($items);
                }

                $this->success("授权成功！");
            } else {
                //当没有数据时，清除当前角色授权
                db("authAccess")->where(["role_id" => $roleId])->delete();
                $this->error("没有接收到数据，执行清除授权成功！");
            }
        }
        //角色ID
        $roleId = $this->request->param("id", 0, 'intval');
        if (empty($roleId)) {
            $this->error("参数错误！");
        }

        $tree = new Tree();
        $tree->icon = ['│ ', '├─ ', '└─ '];
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';

        $result = db('admin_menu')
            ->alias('admin_menu')
            ->select();

        $privilegeData = db("authAccess")->where(["role_id" => $roleId, 'type' => 'admin_url'])->column("rule_name");//获取权限表数据

        $role = db('role')->find($roleId);
        $departments = getParent('department',$role['department_id'],['id','lvl','is_company']);
        $parent = [];
        foreach ($departments as $department) {
            if($department['is_company']) {
                $parent = $department;
                $departmentData = db("authAccess")->where(["role_id" => $department['id'], 'type' => 'company'])->column("rule_name");//获取权限表数据
                break;
            }
        }

        $newMenus      = [];
        $hide = [];
        $res = [];
        foreach ($result as $m) {
            if($parent) {
                if(!$this->_isChecked($m, $departmentData)) {
                    continue;
                }
            }
            if($m['is_hide']){
                $hide[] = $m['id'];
                continue;
            };
            if(in_array($m['parent_id'],$hide)){
                $hide[] = $m['id'];
                continue;
            };
            $res[] = $m;
            $newMenus[$m['id']] = $m;
        }
        $result = $res;

        foreach ($result as $n => $t) {
            $result[$n]['checked'] = ($this->_isChecked($t, $privilegeData)) ? ' checked' : '';
            $result[$n]['level'] = $this->_getLevel($t['id'], $newMenus);
            $result[$n]['style'] = empty($t['parent_id']) ? '' : 'display:none;';
            $result[$n]['parentIdNode'] = ($t['parent_id']) ? ' class="child-of-node-' . $t['parent_id'] . '"' : '';
        }

        $str = "<tr id='node-\$id'\$parentIdNode  style='\$style'>
                   <td style='padding-left:30px;'>\$spacer<input type='checkbox' name='menuId[]' value='\$id' level='\$level' \$checked onclick='javascript:checknode(this);'> \$name</td>
    			</tr>";
        $tree->init($result);

        $category = $tree->getTree(0, $str);

        $roleDepartment = db('role_department')->where([
            'role_id' => $roleId
        ])->find();

        $ids = [];
        foreach ($departments as $department) {
            if($department['is_company']) {
                $ids[] = $department['id'];
            }
        }

        $departmentConfigModel = new DepartmentConfigModel();
        $items = $departmentConfigModel->with('items')->where([
            'pid' => [
                'in',$ids
            ],
            'type' => 1
        ])->select();

        $role_items = db('role_item')->where([
            'role_id' => $roleId
        ])->select();

        $this->assign("category", $category);
        $this->assign("roleDepartment", $roleDepartment);
        $this->assign("roleId", $roleId);
        $this->assign("items", $items);
        $this->assign("role_items", $role_items);
        return $this->fetch();
    }

    /**
     * 检查指定菜单是否有权限
     * @param array $menu menu表中数组
     * @param $privData
     * @return bool
     */
    private function _isChecked($menu, $privData)
    {
        $app = $menu['app'];
        $model = $menu['controller'];
        $action = $menu['action'];
        $name = strtolower("$app/$model/$action");
        if ($privData) {
            if (in_array($name, $privData)) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }

    }

    /**
     * 获取菜单深度
     * @param $id
     * @param array $array
     * @param int $i
     * @return int
     */
    protected function _getLevel($id, $array = [], $i = 0)
    {
        if ($array[$id]['parent_id'] == 0 || empty($array[$array[$id]['parent_id']]) || $array[$id]['parent_id'] == $id) {
            return $i;
        } else {
            $i++;
            return $this->_getLevel($array[$id]['parent_id'], $array, $i);
        }
    }
}